package com.zz.shop.web.controller;

import com.zz.shop.common.Const;
import com.zz.shop.common.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        try {
            Class<? extends HttpServlet> aClass = this.getClass();
            Method target = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(target);
            String response = (String) target.invoke(this, req, resp);
            if (response != null) {
                if (response.contains(Const.FORWARD)) {
                    //转发
                    req.getRequestDispatcher(response.replace(Const.FORWARD, "")).forward(req,resp);
                }
                else if (response.contains(Const.REDIRECT)) {
                    //重定向
                    resp.sendRedirect(response.replace(Const.REDIRECT, ""));
                }else {
                    resp.getWriter().println(response);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            //异常处理
            req.setAttribute(Const.MSG, ResponseResult.createFail("404"));
            req.getRequestDispatcher("message.jsp").forward(req,resp);
        }
    }
}
